import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
// import 'dart:async';

class DatetimeDemo extends StatefulWidget {
  DatetimeDemo({Key key}) : super(key: key);

  @override
  _DatetimeDemoState createState() => _DatetimeDemoState();
}

class _DatetimeDemoState extends State<DatetimeDemo> {

  DateTime selectedDate = DateTime.now();
  TimeOfDay selectedTime = TimeOfDay.now();

  void _selectDate() async {
    final DateTime _thisDate = await showDatePicker( // 返回异步对象，使用 async await 把异步变同步
      context: context, 
      initialDate: selectedDate, 
      firstDate: DateTime(1900), 
      lastDate: DateTime(2100),
    );

    if (_thisDate == null) {
      return;
    }

    setState(() {
      selectedDate = _thisDate;
    });
  }

  void _selectTime() async {
    final thisTime = await showTimePicker(
      context: context, 
      initialTime: selectedTime,
    );

    if (thisTime == null) {
      return;
    }

    setState(() {
      selectedTime = thisTime;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("DatetimeDemo"),
        elevation: 0.0,
      ),
      body: Container(
        padding: EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                InkWell(
                  onTap: _selectDate,
                  child: Row(
                    children: [
                      Text(DateFormat.yMMMMd().format(selectedDate)),
                      Icon(Icons.arrow_drop_down),
                    ],
                  ),
                ),
                SizedBox(width: 16.0),
                InkWell(
                  onTap: _selectTime,
                  child: Row(
                    children: [
                      Text(selectedTime.format(context)),
                      Icon(Icons.arrow_drop_down),
                    ],
                  ),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}